package com.gmono.managers;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.Arrays;

public class IEntry {
    public void fillObject(ResultSet row)
    {

        Field[] fs=this.getClass().getDeclaredFields();
        Arrays.stream(fs).forEach(f->{
            Object value=null;
            if(f.getType()==int.class||f.getType()==Integer.class) try {
                value=row.getInt(f.getName());
            } catch (SQLException e) {
                e.printStackTrace();
            }
            else if(f.getType()==String.class) try {
                value=row.getString(f.getName());
            } catch (SQLException e) {
                e.printStackTrace();
            }
            else if(f.getType()== LocalDateTime.class) try {
                value=row.getTimestamp(f.getName()).toLocalDateTime();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                f.set(this,value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        });
    }

    public static <T extends IEntry> T getObject(Class type,ResultSet row)  {
        T ret= null;
        try {
            ret = (T) type.getConstructors()[0].newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        ret.fillObject(row);
        return ret;
    }
}
